<!--使用微信自导功能扫一扫进入此页面-->
<template>
	<view class="me-div">
	    <!--未登陆-->
		<div class='unlogin' v-if='!userInfo'>
			<image src="/static/img/unlogin.png" mode=""></image>
			<button type="primary" open-type='getUserInfo' @getuserinfo="onLogin">登陆</button>
		</div>
		
		<MyRight />
	</view>
</template>

<script>
import MyRight from '@/components/myright.vue';
import {post,setLocalStorage,getLocalStorage,showToast} from '../../utils/index.js';
import {loginUrl,addMyPartnerUrl} from '../../config.js';
import {mapActions} from 'vuex';
export default {
	data(){
		return {
			uid: '',  //被扫码用户的uid
			userInfo: '',
		}
	},
	components: {
		MyRight
	},
	onShow(){
		let self = this;
		this.uid = this.$mp.query.uid;
		var userInfo = getLocalStorage('userInfo');
		if(userInfo && this.uid){
			this.userInfo = userInfo;
			this.$store.dispatch('setUserInfo', userInfo);
			self.setMyPartner();
			uni.redirectTo({
				url: '/pages/newpackage/index?uid='+self.uid
			});
		}
	},
	methods: {
		//将该小伙伴设置为我的小伙伴
		setMyPartner(){
			var self = this;
			post(addMyPartnerUrl, {
				session_token: self.userInfo.session_token,
				id: self.uid  //伙伴的id
			})
			.then((res)=>{
				if(res.code==200){
					//这里还需要处理寄件人信息
					uni.redirectTo({
						url: '/pages/newpackage/index?uid='+self.uid
					});
				}else{
					showToast(res.errMsg);
				}
			});
		},
		//获取用户信息，登陆
		onLogin(e){
			var self = this;
			var getData = e.target;  //用户信息都在这里
			//授权登陆，获取用户信息
			new Promise((resolve, reject)=>{
			    wx.login({
			        success: function(res){
			            var code = res.code;
			            resolve(code);
			        }
			    });
			})
			.then((code)=>{
				uni.showLoading({
					title: '登陆中...'
				});
				let obj = {
				    iv: getData.iv,
				    code: code,
				    encryptedData: getData.encryptedData,
				    rawData: getData.rawData,
				    signature: getData.signature
				};
				post(loginUrl, obj)
				.then((res)=>{
					if(res.code==200){
						let session_token = res.data.session_token;
						let getUserInfo = getData.userInfo;
						let userInfo = {
							avatarUrl: getUserInfo.avatarUrl,
							nickName: getUserInfo.nickName,
							session_token: res.data.session_token,
							telephone: res.data.phone
						};
						self.userInfo = userInfo;
						self.setMyPartner();
						setLocalStorage('userInfo',userInfo);
						self.$store.dispatch('setUserInfo', userInfo);
						uni.redirectTo({
							url: '/pages/newpackage/index?uid='+self.uid
						});
					}else{
						//错误提示
						var errMsg = res.errMsg;
						showToast(errMsg);
					};
				});
			});
		}
	}
}
</script>

<style lang="less">
/**未登录**/
.unlogin{
	text-align: center;
	margin-top:35%;
	image{
		width: 200upx;
		height: 200upx;
	}
	button{
		width: 60%;
	}
}
</style>
